from __future__ import unicode_literals

import unicodedata

from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth import (
    authenticate, get_user_model, password_validation,
)
from django.forms.widgets import TextInput, PasswordInput
# from django.contrib.auth.models import User
from django.utils.translation import ugettext, ugettext_lazy as _

User = get_user_model()


class UsernameField(forms.CharField):
    def to_python(self, value):
        return unicodedata.normalize('NFKC', super(UsernameField, self).to_python(value))


class UserRegisterForm(forms.ModelForm):
    """
    学生注册表单
    """
    password1 = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入确认密码'}),
        strip=False,
        help_text="请输入确认密码")

    password2 = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入确认密码'}),
        strip=False,
        help_text="请输入确认密码",
    )

    class Meta:
        model = User
        fields = ("username",)
        field_classes = {'username': UsernameField}
        widgets = {
            'username': TextInput(attrs={'class': 'form-control', 'placeholder': '请输入您的姓名'}),
        }

    def clean_username(self):
        print("username-----\n", self.cleaned_data)
        return self.cleaned_data.get("username")

    def clean_password2(self):
        print("p2----------\n", self.cleaned_data)
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        print("p2", type(password2), password2)
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("两次密码不一致")
        # self.instance.username = self.cleaned_data.get('username')
        # password_validation.validate_password(self.cleaned_data.get('password2'), self.instance)
        return password2


class UserCreationForm(forms.ModelForm):
    """
    超管创建用户表单
    """
    error_messages = {
        'password_mismatch': "两次密码输入不一致",
    }
    password1 = forms.CharField(
        label="设置密码",
        strip=False,
        widget=forms.PasswordInput,
        help_text=password_validation.password_validators_help_text_html(),
    )
    password2 = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput,
        strip=False,
        help_text="请输入确认密码",
    )

    class Meta:
        model = User
        fields = ("username", "is_staff")
        field_classes = {'username': UsernameField}

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        if self._meta.model.USERNAME_FIELD in self.fields:
            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True})

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        self.instance.username = self.cleaned_data.get('username')
        password_validation.validate_password(self.cleaned_data.get('password2'), self.instance)
        return password2

    # def clean_email(self):
    #     email = self.cleaned_data.get("email")
    #     if User.objects.filter(email=email).exists():
    #         raise forms.ValidationError("邮箱已被使用")
    #     return email

    # def clean_uid(self):
    #     uid = self.cleaned_data.get("uid")
    #     if User.objects.filter(uid=uid).exists():
    #         raise forms.ValidationError("学号已存在")
    #     return uid

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.uid = User.objects.all().order_by("id").last().uid + 1
        print(user.uid)
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """
    管理员修改用户表单
    """

    # 修改密码的表单，未设置，先注释
    # password = ReadOnlyPasswordHashField(label=_('Password'), help_text=_(
    #     'Raw passwords are not stored, so there is no way to see '
    #     'this user\'s password, but you can change the password '
    #     'using <a href=\"password/\">this form</a>.'))

    class Meta:
        model = get_user_model()
        exclude = ()

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)
        f = self.fields.get('user_permissions', None)
        if f is not None:
            f.queryset = f.queryset.select_related('content_type')

    def clean_password(self):
        return self.initial['password']
